﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using A2DFramework.HttpLoadBalancer.HttpProtocal;

namespace A2DFramework.HttpLoadBalancer.HttpProtocal
{
    public class HttpHeadersCollection : List<HttpHeaderEntity>
    {
        public HttpHeaderEntity? Connection
        {
            get
            {
                return SearchHeaderByKey("Connection");
            }
        }
        public HttpHeaderEntity? ContentLength
        {
            get
            {
                return SearchHeaderByKey("Content-Length");
            }
        }
        public HttpHeaderEntity? TransferEncoding
        {
            get
            {
                return SearchHeaderByKey("Transfer-Encoding");
            }
        }

        private HttpHeaderEntity? SearchHeaderByKey(string key)
        {
            foreach (HttpHeaderEntity header in this)
            {
                if (header.Key.Equals(key, StringComparison.OrdinalIgnoreCase))
                    return header;
            }

            return null;
        }
        private void AddOrUpdateHeader(string key, string value)
        {
            HttpHeaderEntity? header = SearchHeaderByKey(key);
            if (header == null)
            {
                this.Add(new HttpHeaderEntity() { Key = key, Value = value });
            }
            else
            {
                this.RemoveHeader(key);
                this.Add(new HttpHeaderEntity() { Key = key, Value = value });
            }
        }


        public void SetHeader(string key, string value)
        {
            AddOrUpdateHeader(key, value);
        }
        public HttpHeaderEntity? GetHeader(string key)
        {
            HttpHeaderEntity? header = SearchHeaderByKey(key);

            if (header == null)
                return null;

            return header;
        }
        public void RemoveHeader(string key)
        {
            HttpHeaderEntity? header = SearchHeaderByKey(key);

            if (header == null)
                return;

            this.Remove(header.Value);
        }
    }
}
